package com.woniuxy.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.hc.entity.*;
import com.hc.utils.ResponseEntity;
import com.woniuxy.user.dto.*;
import com.woniuxy.user.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

@RestController
@RequestMapping({"/user"})
@CrossOrigin
public class UserController {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    //注入阿里云客户端
    @Resource
    private OSSClient ossClient;

    //指定桶的名字
    private static final String BUCKETNAME="tanbenxu";
    //指定文件URL的前缀
    private static final String BASE_URL ="https://tanbenxu.oss-cn-chengdu.aliyuncs.com";
    @Resource
    private BlackListService blackListService;
    @Resource
    private ReportInforService reportInforService;
    @Resource
    private UserService userService;
    @Resource
    private FollowService followService;
    @Resource
    private OrderService orderService;
    @Resource
    private PaperService paperService;
    @Resource
    private NoticeClassService noticeClassService;
    //拉黑用户
    @PostMapping("/blackLists")
    public ResponseEntity<Boolean> blackLists(@RequestBody BlackList blackList) {
        ResponseEntity<Boolean> entity;
        int flag = blackListService.insertBlackList(blackList);
        if(flag>0){
            entity=ResponseEntity.SUCCESS;
            entity.setData(true);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(false);
        return entity;
    }
    //举报用户
    @PostMapping("/reportUser")
    public ResponseEntity<Boolean> reportUser(@RequestBody ReportInfor reportInfor) {
        ResponseEntity<Boolean> entity;
        int flag = reportInforService.reportUser(reportInfor);
        if(flag>0){
            entity=ResponseEntity.SUCCESS;
            entity.setData(true);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(false);
        return entity;
    }
    //获取该用户关注的好友
    @GetMapping("/getFollowUser/{uid}")
    public ResponseEntity<List<UserTwo>> getFollowUser(@PathVariable("uid") Integer id) {
        List<UserTwo> users = userService.findFollowedUserByUserId(id);
        ResponseEntity<List<UserTwo>> entity;
        if(users.size()>0){
            entity=ResponseEntity.SUCCESS;
            entity.setData(users);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(null);
        return entity;
    }
    //取消关注
    @DeleteMapping("/cancelFollow")
    public ResponseEntity<Boolean> cancelFollow(@RequestBody Follow follow) {
        int flag =followService.cancelFollow(follow);
        ResponseEntity<Boolean> entity;
        if(flag>0){
            entity=ResponseEntity.SUCCESS;
            entity.setData(true);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(false);
        return entity;
    }
    //获取用户私信的用户
    @GetMapping("/getPrivateLetterUser/{uid}")
    public ResponseEntity getLetterUser(@PathVariable("uid") Integer id) {
        List<UserTwo> users = userService.findLetterUserByUserId(id);
        ResponseEntity<List<UserTwo>> entity;
        if(users.size()>0){
            entity=ResponseEntity.SUCCESS;
            entity.setData(users);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(null);
        return entity;
    }
    //添加关注
    @PostMapping("/follow")
    public ResponseEntity addFollow(@RequestBody Follow follow) {
        followService.addFollow(follow);
        return ResponseEntity.SUCCESS;
    }


    //推送共同关注好友
    @GetMapping("/commonfriend/{uid}")
    public ResponseEntity commonFriends(@PathVariable("uid") Integer id){
        List<String> collectnames = new ArrayList<>();
        SetOperations<String, Object> ops = redisTemplate.opsForSet();
        List<Follow> friends = userService.findCommonFriendByUserId(id);
        //关注好友必须大于两个以上才开启推送共同好友
        if(friends.size()>2){
            for (Follow friend : friends) {
                collectnames.add("关注"+friend.getFollowId());
                ops.add("关注"+id,friend.getFollowId());
                List<Follow> friends1 = userService.findCommonFriendByUserId(friend.getFollowId());
                for (Follow follow : friends1) {
                    ops.add("关注"+friend.getFollowId(),follow.getFollowId());
                }
            }

            //产生不重复的3个随机数（在三个关注好友里找到共同关注的好友而用户没有就推送给他）
            Random r = new Random();
            List<Integer> nums = new ArrayList();//保存生成的随机数
            while (nums.size()<3){
                int num = r.nextInt(collectnames.size());
                if(!nums.contains(num)){
                    nums.add(num);
                }
            }

            List<String> names = new ArrayList();
            for (int i=0;i<3;i++){
                names.add(collectnames.get(nums.get(i)));
            }
            Set<Object> i = ops.intersect(names);
            Object[] array = i.toArray();
            System.out.println(Arrays.toString(array));
            if(array.length!=0){
                int a = (int)array[0];
                Boolean flag = ops.isMember("关注" + id, a);
                if(!flag){
                    User user = userService.findById(a);
                    return new ResponseEntity("200","ok",user);
                }
                return new ResponseEntity("300","暂时没有推荐好友");
            }
            return new ResponseEntity("300","暂时没有推荐好友");
        }
        return new ResponseEntity("300","好友太少，请先加入更多好友");
    }

    //到货通知：  true表到货提醒设置成功，false表到货提醒取消成功
    @PostMapping("/addhasgoodnotice")
    public ResponseEntity addhasGoodNotice(@RequestBody NoticeArriva noticeArriva) {
        boolean b = userService.addHashGoodNotice(noticeArriva);
        return new ResponseEntity("200","ok",b);
    }



    //根据货物id查询是否有设置订阅通知的用户
    @PostMapping("/selectGoodNotice")
    public ResponseEntity selectGoodNotice(@RequestBody NoticeArriva noticeArriva) {
        List<NoticeArriva> noticeArrivas = userService.selectGoodNoticeByGoodsId(noticeArriva);
//        List<User> users=new ArrayList<>();
//        for (int i = 0; i < noticeArrivas.size(); i++) {
//            users.add(noticeArrivas.get(i).getUser());
//        }
        return new ResponseEntity("200","ok",noticeArrivas);
    }
    //查询所有启用的举报分类（status为y）
    @GetMapping("/getAllNoticeWithY")
    public ResponseEntity<List<NoticeClass>> getAllNoticeWithY(){
        ResponseEntity<List<NoticeClass>> entity;
        List<NoticeClass> allNoticeWithY = noticeClassService.getAllNoticeWithY();
        if(allNoticeWithY.size()>0){
            entity=ResponseEntity.SUCCESS;
            entity.setData(allNoticeWithY);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(null);
        return entity;
    }
    //获取用户信息以及其所写文章
    @GetMapping("/getAllOfUserById/{id}")
    public ResponseEntity<UserPaper> getAllOfUserById(@PathVariable("id")Integer id){
        ResponseEntity<UserPaper> entity;
        UserPaper userPaper=userService.getByUserId(id);
        if(userPaper!=null){
            entity=ResponseEntity.SUCCESS;
            entity.setData(userPaper);
            return entity;
        }
        entity=ResponseEntity.FAIL;
        entity.setData(null);
        return entity;
    }
}